package com.zhengyisky.task;

import com.zhengyisky.pojo.Order;
import com.zhengyisky.service.PurchaseService;
import lombok.extern.slf4j.Slf4j;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Component
@Slf4j
public class ImportTask {

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Autowired
    private PurchaseService purchaseService;

    @Autowired
    private RestHighLevelClient restHighLevelClient;

    @Scheduled(cron = "0 0/1 * * * ?")
    public void importData() throws IOException {
        //如果第一次执行，则执行全量同步，如果不是第一次执行增量同步
        String time = stringRedisTemplate.opsForValue().get("month15:last:task");

        List<Order> list = null;


        long currentTime = System.currentTimeMillis();
        stringRedisTemplate.opsForValue().set("month15:last:task", String.valueOf(currentTime));

        if(time == null){
            //第一次执行，全量同步
            list = purchaseService.list();
        }else{

            Date lastTime = new Date(Long.parseLong(time));
            list = purchaseService.listByTime(lastTime);

        }

        if(list != null && list.size()>0){
            log.info("查询到了{}条需要同步的订单信息,当前时间:{}",list.size(), new Date());

            for (Order order : list) {
                IndexRequest indexRequest = new IndexRequest("month2112a","purchase");

                indexRequest.id(order.getOrderCode());

                Map map = new HashMap();
                map.put("name", order.getName());
                map.put("order_code", order.getOrderCode());

                Date signDate = order.getSignDate();
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                map.put("sign_date", sdf.format(signDate));

                indexRequest.source(map);

                restHighLevelClient.index(indexRequest, RequestOptions.DEFAULT);
            }

        }else{
            log.info("没有需要同步的订单信息,当前时间:{}", new Date());
        }

    }
}
